package com.rpframework.module.common.bottom.controller

import com.rpframework.core.json.JsonResp
import com.rpframework.core.json.ParameterException
import com.rpframework.module.common.bottom.entity.Authentication
import com.rpframework.module.common.bottom.entity.po.AuthenticationList
import com.rpframework.module.common.bottom.service.AuthenticationService
import com.rpframework.module.common.url.RequestDescription
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody

@ResponseBody
@RequestMapping
@RequestDescription("角色权限")
@Controller
open class AuthenticationController : BaseController() {
    @Autowired
    lateinit var authenticationService: AuthenticationService

    @RequestMapping
    @RequestDescription("查询角色权限")
    open fun selectByRoleId(roleId: Long): JsonResp<MutableList<Authentication>>? {
        val auth = Authentication()
        auth.roleId = roleId
        return authenticationService.selectsJson(auth)
    }

    @RequestMapping
    @RequestDescription("更新权限")
    open fun update(authenticationList: AuthenticationList): JsonResp<*>? {
        if (authenticationList.authentications.isEmpty())
            throw ParameterException("更新数据是空的")
        authenticationList.authentications.forEach {
            it.roleId ?: throw ParameterException("更新数据值有空的")
        }
        var deleteId = emptySet<Long>()
        var insert = emptySet<Authentication>()

        authenticationList.authentications.forEach {
            deleteId = deleteId.plus(it.roleId)
            insert = insert.plus(it)
        }

        if (deleteId.isNotEmpty()) {
            val example = authenticationService.example
            example.createCriteria().andIn("roleId", deleteId.toList())
            authenticationService.deleteByExample(example)
        }
        if (insert.isNotEmpty()) {
            authenticationService.insertList(insert.toList())
        }
        return JsonResp.ok("更新成功")
    }
}